package com.erji.admin.controller.applet;

import com.erji.admin.domain.dto.AppletBindDTO;
import com.erji.admin.domain.dto.AppletLoginDTO;
import com.erji.admin.domain.dto.AppletLoginUser;
import com.erji.admin.domain.entity.AppletUserPO;
import com.erji.admin.domain.vo.AppletLoginResultVO;
import com.erji.admin.domain.vo.AppletUserVO;
import com.erji.admin.service.AppletTokenService;
import com.erji.admin.service.AppletUserService;
import com.erji.common.constant.StringPool;
import com.erji.common.core.domain.R;
import com.erji.common.utils.SecurityUtils;
import com.erji.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 会员管理Controller
 */

@Api(tags = "会员登录注册管理", description = "会员登录注册管理")
@RestController
@RequestMapping("/applet/v1/user")
public class AppletUserController {

    @Autowired
    private AppletUserService appletUserService;

    @Autowired
    private AppletTokenService appletTokenService;

    @ApiOperation("会员绑定")
    @PostMapping("/bind")
    public R<String> bind(@RequestBody AppletBindDTO appletBindDTO) {
        appletUserService.bind(appletBindDTO);
        return R.ok();
    }

    @ApiOperation("会员小程序登录")
    @PostMapping("/login")
    public R<AppletLoginResultVO> login(@RequestBody @Validated AppletLoginDTO appletLoginDTO) {
        return R.ok(appletUserService.login(appletLoginDTO));
    }

    @ApiOperation("会员小程序获取手机号")
    @PostMapping("/getPhoneNumber")
    public R<Map<String, String>> getPhoneNumber(@RequestBody @Validated AppletLoginDTO appletLoginDTO) {
        return R.ok(appletUserService.getPhoneNumber(appletLoginDTO));
    }

    @ApiOperation("获取会员信息")
    @GetMapping("/info")
    public R<AppletUserVO> info() {
        return R.ok(appletUserService.getAppletUserInfo());
    }

    @ApiOperation("登出")
    @DeleteMapping("/logout")
    public R<?> logout() {
        // 删除用户缓存记录
        appletTokenService.delLoginUser(SecurityUtils.getLoginUser().getToken());
        return R.ok(StringPool.YES);
    }

    @ApiOperation(value = "刷新token")
    @GetMapping("/refreshToken")
    public R<String> refreshToken(HttpServletRequest request) {
        AppletLoginUser loginUser = appletTokenService.getLoginUser(request);

        String userId = SecurityUtils.getUserId();
        AppletUserPO appletUserPO = appletUserService.fetchById(userId);
        if (StringUtils.isNotNull(appletUserPO)) {
            // 刷新令牌有效期
            appletTokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }
}
